package com.kingint.web.listener.repair;

import com.kingint.mbg.ser.entity.SerWorkOrder;
import com.kingint.mbg.ser.mapper.SerWorkOrderMapper;
import com.kingint.web.util.spring.SpringContextHolder;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.util.StringUtils;

/**
 * 维修单创建监听器
 */
public class RepairCreateListener implements TaskListener {

    @Override
    public void notify(DelegateTask delegateTask) {
        SerWorkOrderMapper orderMapper = SpringContextHolder.getBean(SerWorkOrderMapper.class);
        String processInstanceId = delegateTask.getProcessInstanceId();//流程实例id
        String eventName = delegateTask.getEventName();//获取事件名称
        RuntimeService runtimeService = SpringContextHolder.getBean(RuntimeService.class);
        ProcessInstance instance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        //设置参数
        Object completeStatus1 = delegateTask.getVariable("completeStatus");
        Object receiveStatus = delegateTask.getVariable("receiveStatus");
        Object rejectStatus = delegateTask.getVariable("rejectStatus");
        if(StringUtils.isEmpty(completeStatus1)){
            delegateTask.setVariable("completeStatus",-1);
        }
        if(StringUtils.isEmpty(receiveStatus)){
            delegateTask.setVariable("receiveStatus",-1);
        }
        if(StringUtils.isEmpty(rejectStatus)){
            delegateTask.setVariable("rejectStatus",-1);
        }
        if (eventName.equals("complete")) {//创建时调用
            String completeStatus = delegateTask.getVariable("completeStatus").toString();
            if (!StringUtils.isEmpty(instance)) {
                if (completeStatus != null && completeStatus.equals("0")) {
                    String businessKey = instance.getBusinessKey();
                    String[] s = businessKey.split("_");
                    Integer integer = Integer.valueOf(s[2]);//workId
                    SerWorkOrder workOrder = new SerWorkOrder();
                    workOrder.setId(integer);
                    workOrder.setOrderStatus(6);//待确认
                    orderMapper.updateById(workOrder);//更新相关额状态
                }
            }
        }
    }
}
